<route lang="json5">
{
  layout: 'default',
  style: {
    navigationBarTitleText: '审批管理',
  },
}
</route>

<script setup lang="ts">
import type { IOrder } from '@/api/interface/rescue/order/order'
import { computed, onMounted, ref } from 'vue'
import { getOrderListApi } from '@/api/modules/rescue/order/order'
import OrderCard from '@/components/rescue/order/OrderCard.vue'
import OrderReviewDialog from '@/components/rescue/order/OrderReviewDialog.vue'
import { OrderReviewStatus } from '@/enums/rescue/OrderReviewStatus'

// 页面状态
const pageLoaded = ref(false)
const cardsVisible = ref(false)
const loading = ref(false)
const refreshing = ref(false)

// 审批列表数据
const reviewList = ref<IOrder.OrderVO[]>([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const hasMore = ref(true)

// 筛选参数
const filterParams = ref({
  page: 1,
  limit: 10,
  statusList: [] as string[],
  searchType: 'workNumber',
  searchText: '',
  workNumber: '',
  orderNumber: '',
})

// 详情弹窗状态
const showDetail = ref(false)
const selectedOrderId = ref<number | undefined>(undefined)

// 审批弹窗状态
const showReviewDialog = ref(false)
const reviewingOrder = ref<IOrder.OrderVO | null>(null)

// 统计数据
const statistics = computed(() => {
  const stats = {
    pending: 0,
    approved: 0,
    rejected: 0,
    total: reviewList.value.length,
  }

  reviewList.value.forEach((item) => {
    switch (item.status) {
      case 'OutboundApply':
      case 'InboundApply':
        stats.pending++
        break
      case 'OutboundApprove':
      case 'InboundApprove':
      case 'OutboundComplete':
      case 'InboundComplete':
        stats.approved++
        break
      case 'Terminate':
        stats.rejected++
        break
    }
  })

  return stats
})

// 计算属性
const filteredList = computed(() => {
  return reviewList.value.filter((item) => {
    // 状态筛选：如果有选择具体状态，则进行筛选；如果是空数组（全部状态），则不筛选
    if (
      filterParams.value.statusList.length > 0 &&
      !filterParams.value.statusList.includes(item.status)
    ) {
      return false
    }
    if (filterParams.value.workNumber && !item.workNumber.includes(filterParams.value.workNumber)) {
      return false
    }
    if (
      filterParams.value.orderNumber &&
      !item.orderNumber.includes(filterParams.value.orderNumber)
    ) {
      return false
    }
    return true
  })
})

// 获取审批列表
async function getReviewList(loadMore = false) {
  try {
    loading.value = true

    const params = {
      ...filterParams.value,
      page: loadMore ? currentPage.value : 1,
      limit: pageSize.value,
    }

    const result = await getOrderListApi(params)

    // 添加测试数据（仅用于测试）
    const testData = [
      {
        id: 1,
        orderNumber: 'TEST001',
        workNumber: 'WORK001',
        status: 'OutboundApply',
        reason: '测试出库申请',
        applyName: '张三',
        applyPhone: '13800138000',
        totalAmount: 10,
        totalPrice: 1000,
        createTime: new Date().toISOString(),
        updateTime: new Date().toISOString(),
      },
      {
        id: 2,
        orderNumber: 'TEST002',
        workNumber: 'WORK002',
        status: 'InboundApply',
        reason: '测试入库申请',
        applyName: '李四',
        applyPhone: '13900139000',
        totalAmount: 5,
        totalPrice: 500,
        createTime: new Date().toISOString(),
        updateTime: new Date().toISOString(),
      },
    ]

    if (loadMore) {
      reviewList.value = [...reviewList.value, ...(result.data?.rows || testData)]
    } else {
      reviewList.value = result.data?.rows || testData
    }

    total.value = result.data?.total || 2
    hasMore.value = reviewList.value.length < total.value

    if (loadMore) {
      currentPage.value++
    }
  } catch (error) {
    console.error('获取审批列表失败:', error)
    uni.showToast({
      title: '获取审批列表失败',
      icon: 'none',
    })
  } finally {
    loading.value = false
    refreshing.value = false
  }
}

// 查看申请详情
function viewDetail(item: IOrder.OrderVO) {
  selectedOrderId.value = item.id
  showDetail.value = true
}

// 处理审批
function handleReview(item: IOrder.OrderVO) {
  reviewingOrder.value = item
  showReviewDialog.value = true
}

// 审批成功回调
function handleReviewSuccess() {
  // 刷新列表
  currentPage.value = 1
  getReviewList(false)
}

// 下拉刷新
function onRefresh() {
  refreshing.value = true
  currentPage.value = 1
  getReviewList(false)
}

// 加载更多
function onLoadMore() {
  if (hasMore.value && !loading.value) {
    getReviewList(true)
  }
}

// 筛选状态变化
function onStatusChange(statusList: string[]) {
  filterParams.value.statusList = statusList
  currentPage.value = 1
  getReviewList(false)
}

// 搜索
function onSearch() {
  currentPage.value = 1
  getReviewList(false)
}

// 重置筛选条件
function resetFilters() {
  filterParams.value = {
    page: 1,
    limit: 10,
    statusList: [],
    searchType: 'workNumber',
    searchText: '',
    workNumber: '',
    orderNumber: '',
  }
  currentPage.value = 1
  getReviewList(false)
}

// 页面加载动画
function startPageAnimation() {
  pageLoaded.value = true
  setTimeout(() => {
    cardsVisible.value = true
  }, 400)
}

onMounted(() => {
  startPageAnimation()
  getReviewList(false)
})
</script>

<template>
  <view class="review-page" :class="{ loaded: pageLoaded }">
    <!-- 毛玻璃背景 -->
    <view class="page-background">
      <view class="bg-blur" />
      <view class="bg-gradient" />
    </view>

    <!-- 页面头部 -->
    <view class="page-header" :class="{ visible: pageLoaded }">
      <view class="header-content">
        <view class="title-section">
          <text class="page-title">审批管理</text>
          <text class="page-subtitle">Review Management</text>
        </view>
        <view class="header-actions">
          <view class="refresh-btn" @tap="onRefresh">
            <wd-icon name="refresh" size="22px" color="#1D1D1F" />
          </view>
        </view>
      </view>
    </view>

    <!-- 统计卡片 -->
    <view class="statistics-section" :class="{ visible: pageLoaded }">
      <view class="stats-container">
        <view class="stat-card">
          <view class="card-background">
            <view class="card-blur" />
          </view>
          <view class="stat-content">
            <view class="stat-icon pending">
              <wd-icon name="clock" size="24px" color="#FF9500" />
            </view>
            <view class="stat-info">
              <text class="stat-number">
                {{ statistics.pending }}
              </text>
              <text class="stat-label">待审批</text>
            </view>
          </view>
        </view>

        <view class="stat-card">
          <view class="card-background">
            <view class="card-blur" />
          </view>
          <view class="stat-content">
            <view class="stat-icon approved">
              <wd-icon name="check-circle" size="24px" color="#34C759" />
            </view>
            <view class="stat-info">
              <text class="stat-number">
                {{ statistics.approved }}
              </text>
              <text class="stat-label">已通过</text>
            </view>
          </view>
        </view>

        <view class="stat-card">
          <view class="card-background">
            <view class="card-blur" />
          </view>
          <view class="stat-content">
            <view class="stat-icon rejected">
              <wd-icon name="close-circle" size="24px" color="#FF3B30" />
            </view>
            <view class="stat-info">
              <text class="stat-number">
                {{ statistics.rejected }}
              </text>
              <text class="stat-label">已拒绝</text>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 筛选器 -->
    <view class="filter-section" :class="{ visible: cardsVisible }">
      <OrderFilter
        v-model="filterParams"
        :show-status="true"
        :show-search="true"
        :default-expanded="true"
        @search="onSearch"
        @reset="resetFilters"
        @status-change="onStatusChange"
      />
    </view>

    <!-- 审批列表 -->
    <view class="review-list-section" :class="{ visible: cardsVisible }">
      <view class="section-header">
        <text class="section-title">申请列表</text>
        <text class="section-subtitle">Pending Applications</text>
      </view>

      <view v-if="loading && reviewList.length === 0" class="loading-container">
        <wd-loading />
        <text class="loading-text">加载中...</text>
      </view>

      <view v-else-if="filteredList.length === 0" class="empty-container">
        <wd-icon name="inbox" size="64px" color="#C7C7CC" />
        <text class="empty-text">暂无申请记录</text>
      </view>

      <view v-else class="review-list">
        <OrderCard
          v-for="(item, index) in filteredList"
          :key="item.id"
          :order="item"
          :show-applicant="true"
          :show-price="true"
          :show-review-button="true"
          class="review-item"
          :style="{ 'animation-delay': `${index * 0.1}s` }"
          @click="viewDetail"
          @review="handleReview"
        />
      </view>

      <!-- 加载更多 -->
      <view v-if="hasMore && reviewList.length > 0" class="load-more-container">
        <wd-button type="primary" size="large" :loading="loading" @tap="onLoadMore">
          {{ loading ? '加载中...' : '加载更多' }}
        </wd-button>
      </view>
    </view>

    <!-- 详情弹窗 -->
    <OrderDetail v-model="showDetail" :order-id="selectedOrderId" />

    <!-- 审批弹窗 -->
    <OrderReviewDialog
      :id="reviewingOrder?.id"
      v-model="showReviewDialog"
      :order-info="{
        orderNumber: reviewingOrder?.orderNumber || '',
        reason: reviewingOrder?.reason || '',
        applyName: reviewingOrder?.applyName || '',
      }"
      @success="handleReviewSuccess"
    />

    <!-- 底部安全区域 -->
    <view class="safe-area-bottom" />
  </view>
</template>

<style lang="scss" scoped>
// Apple设计系统颜色
$system-blue: #007aff;
$system-green: #34c759;
$system-orange: #ff9500;
$system-purple: #af52de;
$system-red: #ff3b30;
$system-gray: #8e8e93;
$system-gray2: #aeaeb2;
$system-gray3: #c7c7cc;
$system-gray4: #d1d1d6;
$system-gray5: #e5e5ea;
$system-gray6: #f2f2f7;

// 文本颜色
$label-primary: #000000;
$label-secondary: rgba(60, 60, 67, 0.6);
$label-tertiary: rgba(60, 60, 67, 0.3);

// 背景颜色
$background-primary: #ffffff;
$background-secondary: #f2f2f7;
$background-tertiary: #ffffff;

// 分割线和边框
$separator: rgba(60, 60, 67, 0.36);
$separator-opaque: #c6c6c8;

// 页面容器
.review-page {
  min-height: 100vh;
  background: $background-secondary;
  position: relative;
  overflow: hidden;
}

// 背景效果
.page-background {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 0;

  .bg-blur {
    position: absolute;
    top: -50%;
    left: -50%;
    width: 200%;
    height: 200%;
    background: radial-gradient(ellipse at center, rgba(255, 59, 48, 0.05) 0%, transparent 70%);
    animation: breathe 15s infinite ease-in-out;
  }

  .bg-gradient {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 60%;
    background: linear-gradient(
      180deg,
      rgba(255, 255, 255, 0.8) 0%,
      rgba(242, 242, 247, 0.4) 50%,
      transparent 100%
    );
    backdrop-filter: blur(20px);
  }
}

// 页面头部
.page-header {
  background: rgba(255, 255, 255, 0.85);
  backdrop-filter: blur(20px);
  -webkit-backdrop-filter: blur(20px);
  padding: 88rpx 40rpx 36rpx;
  border-bottom: 0.5px solid $separator;
  position: relative;
  z-index: 10;
  opacity: 0;
  transform: translateY(-30rpx);
  transition: all 1s cubic-bezier(0.23, 1, 0.32, 1);

  &.visible {
    opacity: 1;
    transform: translateY(0);
  }

  .header-content {
    display: flex;
    justify-content: space-between;
    align-items: flex-end;
  }

  .title-section {
    .page-title {
      display: block;
      font-size: 54rpx;
      font-weight: 700;
      color: $label-primary;
      line-height: 1.1;
      margin-bottom: 6rpx;
      letter-spacing: -0.5px;
    }

    .page-subtitle {
      font-size: 26rpx;
      color: $label-secondary;
      font-weight: 500;
      letter-spacing: 0.2px;
    }
  }

  .header-actions {
    .refresh-btn {
      width: 72rpx;
      height: 72rpx;
      background: rgba(0, 122, 255, 0.08);
      border-radius: 18rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      transition: all 0.2s cubic-bezier(0.25, 0.46, 0.45, 0.94);
      border: 0.5px solid rgba(0, 122, 255, 0.1);

      &:active {
        transform: scale(0.92);
        background: rgba(0, 122, 255, 0.15);
      }
    }
  }
}

// 统计区域
.statistics-section {
  padding: 32rpx 40rpx;
  position: relative;
  z-index: 5;
  opacity: 0;
  transform: translateY(30rpx);
  transition: all 1s cubic-bezier(0.23, 1, 0.32, 1) 0.2s;

  &.visible {
    opacity: 1;
    transform: translateY(0);
  }

  .stats-container {
    display: flex;
    gap: 16rpx;
  }

  .stat-card {
    flex: 1;
    position: relative;
    border-radius: 20rpx;
    overflow: hidden;
    border: 0.5px solid rgba(255, 255, 255, 0.8);
    box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);

    .card-background {
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;

      .card-blur {
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: rgba(255, 255, 255, 0.75);
        backdrop-filter: blur(20px);
        -webkit-backdrop-filter: blur(20px);
      }
    }

    .stat-content {
      position: relative;
      z-index: 2;
      padding: 28rpx;
      display: flex;
      align-items: center;
      gap: 20rpx;
    }

    .stat-icon {
      width: 56rpx;
      height: 56rpx;
      border-radius: 14rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      flex-shrink: 0;

      &.pending {
        background: rgba(255, 149, 0, 0.1);
      }

      &.approved {
        background: rgba(52, 199, 89, 0.1);
      }

      &.rejected {
        background: rgba(255, 59, 48, 0.1);
      }
    }

    .stat-info {
      .stat-number {
        display: block;
        font-size: 42rpx;
        font-weight: 700;
        color: $label-primary;
        line-height: 1.1;
        margin-bottom: 4rpx;
        letter-spacing: -0.5px;
      }

      .stat-label {
        font-size: 22rpx;
        color: $label-secondary;
        font-weight: 500;
      }
    }
  }
}

// 筛选器
.filter-section {
  padding: 32rpx 40rpx;
  position: relative;
  z-index: 5;
  opacity: 0;
  transform: translateY(30rpx);
  transition: all 1s cubic-bezier(0.23, 1, 0.32, 1) 0.3s;

  &.visible {
    opacity: 1;
    transform: translateY(0);
  }
}

// 审批列表区域
.review-list-section {
  padding: 32rpx 40rpx;
  position: relative;
  z-index: 5;
  opacity: 0;
  transform: translateY(30rpx);
  transition: all 1s cubic-bezier(0.23, 1, 0.32, 1) 0.5s;

  &.visible {
    opacity: 1;
    transform: translateY(0);
  }

  .section-header {
    margin-bottom: 32rpx;

    .section-title {
      display: block;
      font-size: 36rpx;
      font-weight: 700;
      color: $label-primary;
      letter-spacing: -0.4px;
      margin-bottom: 6rpx;
    }

    .section-subtitle {
      font-size: 24rpx;
      color: $label-secondary;
      font-weight: 500;
      letter-spacing: 0.1px;
    }
  }

  .loading-container,
  .empty-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 80rpx 20rpx;

    .loading-text,
    .empty-text {
      font-size: 28rpx;
      color: $label-secondary;
      margin-top: 16rpx;
    }
  }

  .review-list {
    .review-item {
      margin-bottom: 24rpx;
      opacity: 0;
      transform: translateY(20rpx);
      animation: slideInUp 0.8s cubic-bezier(0.23, 1, 0.32, 1) forwards;
    }
  }

  .load-more-container {
    padding: 32rpx 0;
    display: flex;
    justify-content: center;
  }
}

// 安全区域
.safe-area-bottom {
  height: 120rpx;
  position: relative;
  z-index: 5;
}

// 动画定义
@keyframes slideInUp {
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes breathe {
  0%,
  100% {
    transform: scale(1) rotate(0deg);
    opacity: 0.3;
  }
  50% {
    transform: scale(1.1) rotate(180deg);
    opacity: 0.6;
  }
}

// 响应式设计
@media (max-width: 750rpx) {
  .page-header {
    padding: 88rpx 32rpx 32rpx;
  }

  .statistics-section,
  .filter-section,
  .review-list-section {
    padding-left: 32rpx;
    padding-right: 32rpx;
  }

  .stats-container {
    gap: 12rpx;
  }

  .stat-card .stat-content {
    padding: 20rpx;
    gap: 16rpx;
  }
}

// 暗色模式支持
@media (prefers-color-scheme: dark) {
  .page-header {
    background: rgba(28, 28, 30, 0.85);
    border-bottom-color: rgba(84, 84, 88, 0.6);
  }

  .stat-card .card-background .card-blur {
    background: rgba(28, 28, 30, 0.9);
  }
}
</style>
